package cn.xjy.ddlc;

import cn.xjy.ddlc.config.DBConnectionConfig;
import cn.xjy.ddlc.loader.MysqlStructureLoader;
import cn.xjy.ddlc.model.Database;
import cn.xjy.ddlc.utils.CloseUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DatabaseStructureLoader {
    
    /**
     * 从数据中加载表结构
     */
    public Database loadDatabase(DBConnectionConfig config) {
        // if ("MySQL".equalsIgnoreCase(config.getType())) {
        String url = String.format("jdbc:mysql://%s:%s?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", config.getHost(), config.getPort());
        String username = config.getUser();
        String password = config.getPassword();
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
            return new MysqlStructureLoader().loadDatabaseStructure(con, config.getDatabase());
        } catch (Exception e) {
            log.error("获取数据库结构出错", e);
        } finally {
            CloseUtils.close(con);
        }
        // }
        return null;
    }
    
    
    public List<String> loadAllDatabaseNames(DBConnectionConfig config) {
        // if ("MySQL".equalsIgnoreCase(config.getType())) {
        String url = String.format("jdbc:mysql://%s:%s?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", config.getHost(), config.getPort());
        String username = config.getUser();
        String password = config.getPassword();
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
            return new MysqlStructureLoader().loadDatabaseNames(con);
        } catch (Exception e) {
            log.error("获取数据库结构出错", e);
        } finally {
            CloseUtils.close(con);
        }
        // }
        return new ArrayList<>();
    }
    
}
